<?php

namespace app\admin\controller\course;

use app\admin\controller\AuthController;
use app\admin\model\course\Course as CourseModel;
use services\UtilService;
use services\UtilService as Util;
use services\JsonService;
use services\FormBuilder as Form;
use think\facade\Route as Url;

/**
 * 课程管理模型
 * Class Course
 * @package app\admin\controller\course
 */
class Course extends AuthController
{

    /**
     * @title 获取所有的课程
     */
    public function index()
    {
        $type = $this->request->param("type");
        if ($type == null) $type = 10;
        $this->assign("course_type", 10);
        // 团体课程数量
        $group_num = CourseModel::where("is_del", "=", 0)->where("course_type", "=", 10)->count();
        // 私教课的数量
        $private_num = CourseModel::where("is_del", "=", 0)->where("course_type", "=", 20)->count();
        // 直播课的数量
        $live_num = CourseModel::where("is_del", "=", 0)->where("course_type", "=", 30)->count();
        $this->assign(compact("type", "group_num", "private_num", "live_num"));
        return $this->fetch();
    }

    /**
     * @title 获取所有的对应的课程
     */
    public function course_list()
    {
        $where = Util::getMore([
            ["page", 1],
            ["limit", 20],
            ['excel', 0],
            ['order', ''],
            ["course_type", $this->request->param("type")]
        ]);
        return JsonService::successlayui(CourseModel::courseList($where));
    }

    /**
     * @tilte 新增课程
     */
    public function create()
    {
        $filed = [
            Form::select("course_type", "课程类型")->setOptions(function () {
                return [
                    ["value" => 10, "label" => "团体课程"],
                    ["value" => 20, "label" => "私教课程"],
                    ["value" => 30, "label" => "直播课程"],
                ];
            }),
            Form::input("course_name", "课程名称"),
            Form::input("course_info", "课程简介"),
            Form::input("keyword", "课程关键字")->placeholder("多个用英文状态下的逗号隔开"),
            Form::frameImageOne('image', '课程图片(305*305px)', Url::buildUrl('admin/widget.images/index', array('fodder' => 'image')))->icon('image')->width('100%')->height('500px'),
            Form::frameImages('slider_image', '产品轮播图(640*640px)', Url::buildUrl('admin/widget.images/index', array('fodder' => 'slider_image')))->maxLength(5)->icon('images')->width('100%')->height('500px')->spin(0),
            Form::number("difficulty", "课程难度")->col(8),
            Form::number("duration", "课程时长")->col(8),
            Form::number("price", "课程价格(学员)")->col(8),
            Form::number('give_integral', '赠送积分')->min(0)->precision(0)->col(8),
            Form::number('sort', '排序')->col(8),
            Form::radio('is_show', '产品状态', 0)->options([['label' => '上架', 'value' => 1], ['label' => '下架', 'value' => 0]])->col(8),

        ];
        $form = Form::make_post_form("添加课程", $filed, Url::buildUrl("save"), 2);
        $this->assign(compact("form"));
        return $this->fetch("public/form-builder");
    }


    /**
     * 编辑课程
     * @param $id
     * @return string|void
     */
    public function edit($id)
    {
        $course = CourseModel::get($id);
        if (!$course) return JsonService::fail("数据不存在");
        $filed = [
            Form::selectOne("course_type", "课程类型", $course->getData("course_type"))->setOptions(function () {
                return [
                    ["value" => 10, "label" => "团体课程"],
                    ["value" => 20, "label" => "私教课程"],
                    ["value" => 30, "label" => "直播课程"],
                ];
            }),
            Form::input("course_name", "课程名称", $course->getData("course_name")),
            Form::input("course_info", "课程简介", $course->getData("course_info")),
            Form::input("keyword", "课程关键字", $course->getData("keyword"))->placeholder("多个用英文状态下的逗号隔开"),
            Form::frameImageOne('image', '产品主图片(305*305px)', Url::buildUrl('admin/widget.images/index', array('fodder' => 'image')), $course->getData('image'))->icon('image')->width('100%')->height('500px'),
            Form::frameImages('slider_image', '产品轮播图(640*640px)', Url::buildUrl('admin/widget.images/index', array('fodder' => 'slider_image')), json_decode($course->getData('slider_image'), 1) ?: [])->maxLength(5)->icon('images')->width('100%')->height('500px'),
            Form::number("difficulty", "课程难度", $course->getData("difficulty"))->col(8),
            Form::number("duration", "课程时长", $course->getData("duration"))->col(8),
            Form::number("price", "课程价格(学员)", $course->getData("price"))->col(8),
            Form::number('give_integral', '赠送积分', $course->getData("give_integral"))->min(0)->precision(0)->col(8),
            Form::number('sort', '排序', $course->getData("sort"))->col(8),
            Form::radio('is_show', '产品状态', $course->getData('is_show'))->options([['label' => '上架', 'value' => 1], ['label' => '下架', 'value' => 0]])->col(8),
        ];
        $form = Form::make_post_form("编辑课程", $filed, Url::buildUrl("update", array("id" => $id)), 2);
        $this->assign(compact("form"));
        return $this->fetch("public/form-builder");
    }

    /**
     * @title 保存新增
     */
    public function save()
    {
        $data = UtilService::getMore([
            ["course_type", ""],
            "course_name",
            "course_info",
            "keyword",
            ["image", []],
            ["slider_image", []],
            ["difficulty", 2],
            ["price", 0],
            ["give_integral", 0],
            ["sort", 0],
            ["is_show", 1],
            ["duration", 0]
        ]);
        if (!$data["course_type"]) return JsonService::fail("请选择课程类型");
        if (!$data["course_name"]) return JsonService::fail("请填写课程名称");
        if (!$data["course_info"]) return JsonService::fail("请填写课程简介");
        $whereData["course_name"] = array("eq", $data["course_name"]);
        $whereData["is_del"] = array("eq", 0);
        $whereData["wxapp_id"] = array("eq", $this->getWxappId());
        $whereData["course_type"] = array("eq", $data["course_type"]);
        if (CourseModel::where($whereData)->find()) return JsonService::fail("课程名称重复");
        if (count($data["image"]) < 1) return JsonService::fail("请上传课程封面图片");
        if (count($data["slider_image"]) < 1) return JsonService::fail("请上传课程轮播图");
        if ($data["price"] == "" || $data["price"] < 0) return JsonService::fail("请填写课程售价");
        if ($data["duration"] == "" || $data["price"] < 0) return JsonService::fail("请填写课程时长");
        $data["image"] = $data["image"][0];
        $data['slider_image'] = json_encode($data['slider_image']);
        $data["add_time"] = time();
        $data["code_path"] = "";
        $data["description"] = "";
        $data["wxapp_id"] = $this->getWxappId();
        $res = CourseModel::create($data);
        if ($res) return JsonService::successful("添加课程成功");
        return JsonService::fail("添加课程失败");
    }

    /**
     * @title 保存修改
     * @param $id
     */
    public function update($id)
    {
        $data = Util::postMore([
            ['course_type', 0],
            'course_name',
            'course_info',
            'keyword',
            ['image', []],
            ['slider_image', []],
            ['price', 0],
            ['sort', 0],
            ['ficti', 100],
            ['give_integral', 0],
            ['is_show', 0],
            ['difficulty', 0],
            ['duration', 0],
        ]);
        if (!$data["course_type"]) return JsonService::fail("请选择课程类型");
        if (!$data["course_name"]) return JsonService::fail("请填写课程名称");
        if (!$data["course_info"]) return JsonService::fail("请填写课程简介");
        if (CourseModel::where("is_del", 0)->where("course_name", $data["course_name"])->where("id", "<>", $id)->where("course_type", $data["course_type"])->find()) return JsonService::fail("课程名称重复");
        if (count($data["image"]) < 1) return JsonService::fail("请上传课程封面图片");
        if (count($data["slider_image"]) < 1) return JsonService::fail("请上传课程轮播图");
        if ($data["price"] == "" || $data["price"] < 0) return JsonService::fail("请填写课程售价");
        if ($data["duration"] == "" || $data["price"] < 0) return JsonService::fail("请填写课程时长");
        $data["image"] = $data["image"][0];
        $data['slider_image'] = json_encode($data['slider_image']);
        CourseModel::edit($data, $id);
        return JsonService::successful('修改成功!');
    }

    /**
     * @param string $is_show
     * @param string $id
     */
    public function set_show($is_show = '', $id = '')
    {
        ($is_show == '' || $id == '') && JsonService::fail('缺少参数');
        $res = CourseModel::where(["id" => $id])->update(["is_show" => $is_show]);
        if ($res) {
            return JsonService::successful($is_show == "1" ? "上架成功" : "下架成功");
        }
        return JsonService::fail($is_show == "1" ? "上架失败" : "下架失败");
    }

    /**
     * @title 编辑详情【富文本】
     * @param $id int 课程的ID
     * @return string|void
     */
    public function edit_content($id)
    {
        if (!$id) return $this->failed("课程不存在");
        $course = CourseModel::get($id);
        if (!$course) return JsonService::fail("课程不存在");
        $this->assign([
            'content' => CourseModel::where('id', $id)->value('description'),
            'field' => 'description',
            'action' => Url::buildUrl('change_field', ['id' => $id, 'field' => 'description'])
        ]);
        return $this->fetch('public/edit_content');
    }

    /**
     * 保存字段
     * @param string $id
     * @param string $filed
     */
    public function change_field($id = "", $description = "")
    {
        $res = CourseModel::where("id", $id)->update(["description" => $description]);
        if ($res) {
            return $this->successful("编辑成功");
        }
        return $this->failed("编辑失败");
    }
}